package com.gears.covfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;

import com.gears.core.util.PropertyUtil;

/**
 * 文档转换类
 * @author Administrator
 * @version 2016年8月10日
 */
public class DocToFdpLibre {

	private static final Integer WORD_TO_PDF_OPERAND = 17;

	private static final Integer PPT_TO_PDF_OPERAND = 32;

	private static final Integer EXCEL_TO_PDF_OPERAND = 0;

	public static String doDocToFdpLibre(String inputLocation,
			String outLocation) throws IOException {
		File inputFile = new File(inputLocation);
//		if (inputFile.getName().endsWith(".doc")
//				|| inputFile.getName().endsWith(".docx")
//				|| inputFile.getName().endsWith(".pptx")
//				|| inputFile.getName().endsWith(".ppt")) {
//			inputFile.getCanonicalPath();
//			outLocation = outLocation.substring(0,
//					outLocation.lastIndexOf(File.separator));
//			String command = PropertyUtil.getConfigureProperties("doc_pdf_command") + " --invisible --convert-to pdf  "
//					+ inputLocation
//					+ " --outdir " + outLocation;
//			System.out.println(command);
//			exeCmd(command);
////			String name = inputLocation.substring(inputLocation.lastIndexOf("\\"),inputLocation.lastIndexOf("."));
////			File file = new File(outLocation+"\\"+name+".pdf");
////			System.out.println(file.exists());
//			return "success";
//		}
		if(inputFile.getName().endsWith(".doc") || inputFile.getName().endsWith(".docx")){
			ActiveXComponent app = null;
			Dispatch doc = null;
			try {
				ComThread.InitSTA();
				app = new ActiveXComponent("Word.Application");
				app.setProperty("Visible", false);
				Dispatch docs = app.getProperty("Documents").toDispatch();
				Object[] obj = new Object[]{
						inputLocation,
						new Variant(false),
						new Variant(false),//是否只读
						new Variant(false),
						new Variant("pwd")
				};
				doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
//          Dispatch.put(doc, "Compatibility", false);  //兼容性检查,为特定值false不正确
				Dispatch.put(doc, "RemovePersonalInformation", false);
				Dispatch.call(doc, "ExportAsFixedFormat", outLocation, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏，值为17

			}catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				if (doc != null) {
					Dispatch.call(doc, "Close", false);
				}
				if (app != null) {
					app.invoke("Quit", 0);
				}
				ComThread.Release();
			}
			return  "success" ;
		}
		if(inputFile.getName().endsWith(".ppt") || inputFile.getName().endsWith(".pptx")){
			ActiveXComponent app = null;
			Dispatch ppt = null;
			try {
				ComThread.InitSTA();
				app = new ActiveXComponent("PowerPoint.Application");
				Dispatch ppts = app.getProperty("Presentations").toDispatch();

            /*
             * call
             * param 4: ReadOnly
             * param 5: Untitled指定文件是否有标题
             * param 6: WithWindow指定文件是否可见
             * */
				ppt = Dispatch.call(ppts, "Open", inputLocation, true,true, false).toDispatch();
				Dispatch.call(ppt, "SaveAs", outLocation, PPT_TO_PDF_OPERAND); // ppSaveAsPDF为特定值32

			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				if (ppt != null) {
					Dispatch.call(ppt, "Close");
				}
				if (app != null) {
					app.invoke("Quit");
				}
				ComThread.Release();
			}
			return "success" ;
		}

		if(inputFile.getName().endsWith(".xls") || inputFile.getName().endsWith(".xlsx")){
			ActiveXComponent ax = null;
			Dispatch excel = null;
			try {
				ComThread.InitSTA();
				ax = new ActiveXComponent("Excel.Application");
				ax.setProperty("Visible", new Variant(false));
				ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
				Dispatch excels = ax.getProperty("Workbooks").toDispatch();

				Object[] obj = new Object[]{
						inputLocation,
						new Variant(false),
						new Variant(false)
				};
				excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

				// 转换格式
				Object[] obj2 = new Object[]{
						new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0
						outLocation,
						new Variant(0)  //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
				};
				Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);

			} catch (Exception es) {
				es.printStackTrace();
				throw es;
			} finally {
				if (excel != null) {
					Dispatch.call(excel, "Close", new Variant(false));
				}
				if (ax != null) {
					ax.invoke("Quit", new Variant[] {});
					ax = null;
				}
				ComThread.Release();
			}
			return  "success" ;
		}
		return "error";
	}

	public static StringBuilder exeCmd(String commandStr) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			Process p = Runtime.getRuntime().exec(commandStr);
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
//			System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return sb;
	}

	@Test
	public void test() throws IOException {
		DocToFdpLibre.doDocToFdpLibre("F:\\360Downloads\\Software\\2.xls","F:\\360Downloads\\Software\\2.pdf") ;
	}
}
